package algorithms.threadpool;

import algorithms.sort.GetRandomArr;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class PoolTest {
    public static void main(String[] args) throws InterruptedException {
        // 处理10000个随机数
        threadPool(10*10*10*1000);

    }

    private static void threadPool(int n) throws InterruptedException {
        int[] arr = GetRandomArr.getRandomArr(n);
        // 原子计数器
        AtomicInteger count = new AtomicInteger();
        // 自定义线程池
        ExecutorService pool = new ThreadPoolExecutor(3,
                5,
                5,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<Runnable>(),
                new ThreadPoolExecutor.CallerRunsPolicy());
        // 开始执行任务
        System.out.println("开始执行任务。。。");
        ThreadLocal<Long> local = new ThreadLocal<>();
        local.set(System.currentTimeMillis());
        for (int e : arr) {
            pool.execute(()->{
                System.out.println("线程:"+Thread.currentThread().getName()+"==>获取到元素："+e);
                count.incrementAndGet();
            });
        }
        pool.shutdown();
        while (true) {
            //Thread.sleep(1000);
            int c = count.get();
            System.out.println("====>处理任务个数:" + c);
            if(c == n) {
                break;
            }
        }

        System.out.println("===>线程池是否关闭："+pool.isShutdown());
        System.out.println("===>运行时常："+(System.currentTimeMillis() - local.get())+" ms");

    }
}
